<?php

namespace backend\models;

use Yii;
use liangzoe\payment\weixin;
use liangzoe\payment\alipay;
use liangzoe\mobilesmser\TextSmser;
use common\models\UserInfo;

/**
 * This is the model class for table "log_refund".
 *
 * @property integer $refund_id
 * @property string $refund_no
 * @property string $third_refund_no
 * @property string $zfb_batch_no
 * @property integer $doing
 * @property string $done_list
 * @property string $transaction_id
 * @property string $trade_no
 * @property integer $uid
 * @property integer $type
 * @property integer $starttime
 * @property integer $endtime
 * @property string $memo_xml
 * @property integer $state
 * @property integer $state_count
 */
class LogRefund extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
	public $username;
	public $file;
	public $refund_amount;
	public $address;
    public static function tableName()
    {
        return 'log_refund';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
          //  [['third_refund_no', 'zfb_batch_no', 'doing', 'done_list'], 'required'],
            [['doing', 'uid', 'type', 'starttime', 'endtime', 'state', 'state_count'], 'integer'],
            [['memo_xml'], 'string'],
            [['refund_no', 'third_refund_no', 'zfb_batch_no', 'transaction_id'], 'string', 'max' => 128],
            [['done_list'], 'string', 'max' => 1000],
            [['offline_file'], 'string', 'max' => 255],
            [['trade_no','username'], 'string', 'max' => 64],
            [['refund_no'], 'unique'],
            [['rmb','offline_rmb'],'number'],
            [['offline_rmb'],'required','on'=>['offline_refund']],
            [['offline_rmb'],'match','pattern'=>'/^[0-9]{1,}\.{0,1}[0-9]{0,2}$/','message'=>'退款金额是保留2位小数的数字'],
            [['file'], 'file','extensions' => 'txt,doc,xls,xlsx,pdf,png,jpg,jpeg,gif,bmp','maxSize'=>'1024*1024*2',
            'tooBig'=>'文件不要超过2M'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'refund_id' => Yii::t('app', 'Refund ID'),
            'refund_no' => Yii::t('app', 'Refund No'),
            'third_refund_no' => Yii::t('app', 'Third Refund No'),
            'zfb_batch_no' => Yii::t('app', 'Zfb Batch No'),
            'doing' => Yii::t('app', 'Doing'),
            'done_list' => Yii::t('app', 'Done List'),
            'transaction_id' => Yii::t('app', 'Transaction ID'),
            'trade_no' => Yii::t('app', 'Trade No'),
            'uid' => Yii::t('app', 'Uid'),
            'type' => Yii::t('app', 'Type'),
            'starttime' => Yii::t('app', 'Starttime'),
            'endtime' => Yii::t('app', 'Endtime'),
            'memo_xml' => Yii::t('app', 'Memo Xml'),
            'state' => Yii::t('app', 'State'),
            'state_count' => Yii::t('app', 'State Count'),
            'rmb' => Yii::t('app', 'Refund Rmb'),
            'offline_rmb' => Yii::t('app', 'Refund Offline Rmb'),
            'offline_file' => Yii::t('app', 'Refund Offline File'),
            'file' => Yii::t('app', 'Refund File'),
        ];
    }
    //场景
    public function scenarios()
    {
    	
    	$scenarios = parent::scenarios();
    	$scenarios['offline_refund'] = ['offline_rmb','offline_file','file','doing','done_list','state','type','trade_no'];
     	return $scenarios;
    }
    //外链支付信息
    public function getPayTradeInfo()
    {
    	return $this->hasOne(PayTrade::className(),['trade_no'=>'trade_no']);
    }
    //外链用户信息
    public function getUserInfo()
    {
    	return $this->hasOne(UserInfo::className(),['id'=>'uid']);
    }
    //微信退款查询
    public function weixin_notify(){  	
   // 	$refund_list = LogRefund::findAll(['state'=>10,'type'=>1]);//已提交到微信平台的退款
    	$refund_list = LogRefund::find()->where("state in (2,4,10) AND type=1")->all();
    	$logpath = Yii::getAlias('@console')."/runtime/logs/notify/";
    	if(!file_exists($logpath))
    		TextSmser::make_dir($logpath);	
    	
    	if(!$refund_list) return false;
    	$weixin_payment = new weixin();
    	foreach ($refund_list as $key=>$val){
    		$result = $weixin_payment->query_refund($val);
    		if(!$result)
    			continue;
    		$result['type']='weixin';
    		file_put_contents($logpath.date('Ymd').".log", json_encode($result)."\n", FILE_APPEND);
    		$refund_one = LogRefund::findOne(['refund_no'=>$val['refund_no']]);
    		
    		$refund_one->endtime = time();
    		$refund_one->memo_xml = json_encode($result);
    		$refund_one->state_count += 1;
    		if($result['result_code'] == 'SUCCESS' && $result['refund_status_0'] == 'SUCCESS'){
    			//echo 'success';
    			$refund_one->state = 20;//退款成功
    			$refund_one->save();
    			//订单状态改变
    			$this->change_trade_state($refund_one->trade_no);	
    		}elseif($result['result_code'] == 'SUCCESS' && $result['refund_status_0'] == 'FAIL'){
    			//echo 'success';
    			$refund_one->state = 30;//退款失败
    			$refund_one->save();
    		}elseif($result['result_code'] == 'FAIL'){
    			//echo "退款号{$val['refund_no']}退款接收失败";
    		}
    	}
    }
    //支付宝退款回调
    public function alipay_notify($request){
    	
    	$logpath = Yii::getAlias('@console')."/runtime/logs/notify/";
    	if(!file_exists($logpath))
    		TextSmser::make_dir($logpath);
    	$request['type'] = 'alipay';
    	file_put_contents($logpath.date('Ymd').".log", json_encode($request)."\n", FILE_APPEND);
    	
    	$batch_no   = 0;  	
    	if(isset($request['batch_no']))
    	{
    		$batch_no = trim($request['batch_no']);
    	}	
    	if (!$batch_no)
    	{
    		/* 无效的通知请求 */
    		return '没有退款批号信息';
    	}
    		
    	 $refund_list = LogRefund::findAll(['zfb_batch_no'=>$batch_no]);
    	 
    	 if(!$refund_list) return '不存在退款信息';
    	 $alipay_payment = new alipay();
    	 //验证信息
    	 $refund_info['batch_no'] = $batch_no;
    	 $notify_result = $alipay_payment->verify_refund_notify($refund_info);
    	 if(!$notify_result) return '验证失败';
    	 
    	 $result_details = $request['result_details'];
    	 $_arr_detail = explode('#', $result_details);//退款明细的数组
    	 foreach ($_arr_detail as $key=>$val){
    	 	$_one_detail = array();
    	 	$_one_detail = explode('^', $val);
    	 	$transaction_id = $_one_detail[0];//支付的交易号
    	 	$refund_fee = $_one_detail[1];
    	 	$refund_status = $_one_detail[2];

    	 	$refund_one = LogRefund::findOne(['transaction_id'=>$transaction_id,'zfb_batch_no'=>$batch_no]);
    	 	$refund_one->endtime = time();
    	 	$refund_one->memo_xml = json_encode($request);
    	 	$refund_one->state_count += 1;
    	 	if($refund_status == 'SUCCESS'){
    	 		$refund_one->state = 20;
    	 		$refund_one->save();
    	 		//订单状态改变
    	 		$this->change_trade_state($refund_one->trade_no);
    	 	}
    	 	else{
    	 		$refund_one->state = 30;
    	 		$refund_one->save();
    	 	}
    	 	
    	 }
    	echo 'success'; 
    }
    /*更改订单状态*/
    public function change_trade_state($trade_no){
    	//分笔全部退款，则更改订单状态
    	if($this->check_state($trade_no))
    	{
    		$trade = PayTrade::findOne(['trade_no'=>$trade_no]);
    		if($trade /*&& $trade['trade_state']==4 && $trade['price_state']==2*/){
    			$trade->price_state = 3;//待退款2->已退款3
    			$trade->trade_state = 5;//退款中4->退款成功5
    			$trade->save();
    			//物流表
    			PayLogistics::updateAll(['logistics_state'=>3],"trade_id={$trade['id']}");
    			//支付表
    			LogPay::updateAll(['state'=>99],"trade_no='{$trade_no}'");
    		}
    	}
    }
    /*验证是否退款成功*/
    public function check_state($trade_no){
    	$refund_state = LogRefund::find()->where(['trade_no'=>$trade_no])->all();
    	foreach ($refund_state as $val){
    		if($val['state'] != 20) return false;
    	}
    	return true;
    }
    function offline_refund($model){

    	$model->done_list .= "，财务退款成功(线下)|".Yii::$app->user->identity->username.
    			"(".Yii::$app->user->identity->id.")|".date('Y-m-d H:i:s',time()).
    			(empty($model->file)?'':'<a href="'.$model->offline_file.'" target="_blank">&nbsp;&nbsp;财务凭证</a>'.'<br/>');
    	$model->state = 20;//退款成功
    	$model->save();

    	$this->change_trade_state($model->trade_no);
    	
    }
}
